package com.video.main_video.manager.handle.comment;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.video.main_video.api.Api;
import com.video.main_video.dao.entity.CommentChild;
import com.video.main_video.dao.entity.CommentReply;
import com.video.main_video.dao.request.comment.CommentChildAddRequest;
import com.video.main_video.dao.response.comment.CommentChildAddResponse;
import com.video.main_video.manager.handle.ApiHandler;
import com.video.main_video.manager.mapper.CommentChildMapper;
import com.video.main_video.manager.mapper.CommentReplyMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Api
@Transactional
public class CommentAddManager implements ApiHandler<CommentChildAddRequest, CommentChildAddResponse> {

    @Autowired
    CommentChildMapper commentChildMapper;

    @Autowired
    CommentReplyMapper replyMapper;

    @Transactional
    @Override
    public CommentChildAddResponse handler(CommentChildAddRequest commentChildAddRequest) {

        addComment(commentChildAddRequest);
        CommentChildAddResponse res = new CommentChildAddResponse();
        res.setCode(200);
        res.setMsg("评论成功");
        return res;
    }

    private void addComment(CommentChildAddRequest dis) {

        CommentChild commentChild = new CommentChild();

//        reply discuss
        if (dis.getParentId() != null) {
            CommentReply reply = new CommentReply();
            BeanUtils.copyProperties(dis, reply);
            replyMapper.insert(reply);
//            update parent count
            updateReplyCount(dis.getParentId());
            return;
        }
        BeanUtils.copyProperties(dis, commentChild);
        commentChildMapper.insert(commentChild);
    }

    private void updateReplyCount(String id) {
        LambdaQueryWrapper<CommentChild> qw = new LambdaQueryWrapper<>();
        qw.eq(CommentChild::getId, id);
        CommentChild dis = commentChildMapper.selectOne(qw);
        Integer replyCount = dis.getReplyCount();
        if (null == replyCount) {
            return;
        }

        CommentChild updateDis = new CommentChild();
        updateDis.setId(id);
        replyCount = replyCount + 1;
        updateDis.setReplyCount(replyCount);

        commentChildMapper.updateById(updateDis);

    }
}
